package com.app.markdown.util;

import com.app.common.MarkdownUtil;
import com.app.common.StringUtil;
import com.app.markdown.store.FileStore;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author 56465
 * @Create 2024/7/30 16:55
 */
public class FileUtil {
    /**
     * 获取默认的目录
     */
    public static String getDefaultDirectory() {
        //return System.getProperty("user.home");
        return "C:\\Users\\56465\\Desktop\\temp";
    }

    /**
     * 打开目录选择器，将选择的目录，展示在 fileListView
     */
    public static void openDirectory(ListView<String> fileListView,WebView fileContentArea) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File selectedDirectory = directoryChooser.showDialog(fileListView.getScene().getWindow());

        if (selectedDirectory != null) {
            FileUtil.displayFilesInDirectory(fileListView, selectedDirectory.getAbsolutePath(), fileContentArea);
        }
    }

    /**
     * 在文件列表视图 fileListView，展示文件列表
     *
     * @param directory
     */
    public static void displayFilesInDirectory(ListView<String> fileListView, String directory, WebView fileContentArea) {
        ObservableList<String> files = FXCollections.observableArrayList();

        try {
            List<Path> filePaths = Files.walk(Paths.get(directory))
                    .filter(path -> path.toString().endsWith(".md"))
                    .toList();

            for (Path path : filePaths) {
                files.add(path.getFileName().toString());
            }

            fileListView.setItems(files);

            // 设置文件选择事件处理器
            fileListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue != null) {
                    displayFileContent(fileContentArea, directory + File.separator + newValue);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在 WebView 中显示文件内容
     * @param directory
     */
    public static void displayFileContent(WebView fileContentArea, String directory) {
        Path filePath = Paths.get(directory);
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath.toFile()))) {
            StringBuilder content = new StringBuilder();
            String line;
            // 保存文件的完整路径
            FileStore.currentFilePathName = directory;
            LinkedList<String> contentList = FileStore.getContentList(directory);
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
                contentList.add(line);
            }
            fileContentArea.getEngine().loadContent(MarkdownUtil.parseMarkdownToHtml(content.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件 WebView fileContentArea;
     */
    public static void saveFileContent(String currentFile) {
        if (!StringUtil.isEmpty(currentFile)) {

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(currentFile))) {
                for (String content : FileStore.getContentList(currentFile)) {
                    writer.write(content);
                }
                writer.flush();
                System.out.println("File saved successfully.");
            } catch (IOException e) {
                // 打印异常信息
                System.err.println("Error saving the file: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
